<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑公司优势</view>
      <view class="nav-right">
        <button class="save-btn" @tap="handleSubmit" :disabled="!canSubmit">
          保存
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 选择数量提示 -->
      <view class="selection-count">
        <text class="count-text">已选择 {{ getTotalSelectedCount() }}/10</text>
      </view>

      <!-- 公司优势 -->
      <view class="form-item">
        <view class="form-label">公司优势</view>
        <view v-if="companyAdvantageList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in companyAdvantageList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: isAdvantageSelected(item.dataKey) }"
            @tap="toggleAdvantage(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>

      <!-- 福利待遇 -->
      <view class="form-item">
        <view class="form-label">福利待遇</view>
        <view v-if="companyWelfareList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in companyWelfareList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: isWelfareSelected(item.dataKey) }"
            @tap="toggleWelfare(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>

      <!-- 薪资福利 -->
      <view class="form-item">
        <view class="form-label">薪资福利</view>
        <view v-if="salaryBenefitList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in salaryBenefitList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: isSalaryBenefitSelected(item.dataKey) }"
            @tap="toggleSalaryBenefit(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>

      <!-- 补助津贴 -->
      <view class="form-item">
        <view class="form-label">补助津贴</view>
        <view v-if="subsidyAllowanceList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in subsidyAllowanceList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: isSubsidyAllowanceSelected(item.dataKey) }"
            @tap="toggleSubsidyAllowance(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { modifyCompanyInfoApi, getDictionaryDataListByTypesApi } from "@/api/company.js";

// 获取页面参数
const companyId = ref('');
const initialData = ref({});

// 表单数据
const formData = ref({
  advantage: [],      // 存储字典数据ID
  benefits: [],       // 存储字典数据ID
  bonus: [],          // 存储字典数据ID
  subsidy: []         // 存储字典数据ID
});

// 公司优势相关数据
const companyAdvantageList = ref([]);
const companyWelfareList = ref([]);
const salaryBenefitList = ref([]);
const subsidyAllowanceList = ref([]);

// 是否可以提交
const canSubmit = computed(() => {
  return true; // 公司优势相关字段都不是必填的
});

// 加载公司优势相关字典数据
const loadCompanyAdvantageData = async () => {
  try {
    const data = await getDictionaryDataListByTypesApi([
      'company_advantage',
      'company_welfare', 
      'salary_benefit',
      'subsidy_allowance'
    ]);
    
    if (data) {
      companyAdvantageList.value = (data.company_advantage || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
      companyWelfareList.value = (data.company_welfare || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
      salaryBenefitList.value = (data.salary_benefit || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
      subsidyAllowanceList.value = (data.subsidy_allowance || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
    } else {
      console.warn('公司优势相关数据为空或格式不正确');
      companyAdvantageList.value = [];
      companyWelfareList.value = [];
      salaryBenefitList.value = [];
      subsidyAllowanceList.value = [];
    }
  } catch (error) {
    console.error('加载公司优势相关数据失败:', error);
    companyAdvantageList.value = [];
    companyWelfareList.value = [];
    salaryBenefitList.value = [];
    subsidyAllowanceList.value = [];
  }
};

// 公司优势相关标签选择方法
const toggleAdvantage = (item) => {
  const index = formData.value.advantage.indexOf(item.dataKey);
  if (index > -1) {
    formData.value.advantage.splice(index, 1);
  } else {
    if (getTotalSelectedCount() < 10) {
      formData.value.advantage.push(item.dataKey);
    } else {
      uni.showToast({
        title: '最多只能选择10个标签',
        icon: 'none'
      });
    }
  }
};

const toggleWelfare = (item) => {
  const index = formData.value.benefits.indexOf(item.dataKey);
  if (index > -1) {
    formData.value.benefits.splice(index, 1);
  } else {
    if (getTotalSelectedCount() < 10) {
      formData.value.benefits.push(item.dataKey);
    } else {
      uni.showToast({
        title: '最多只能选择10个标签',
        icon: 'none'
      });
    }
  }
};

const toggleSalaryBenefit = (item) => {
  const index = formData.value.bonus.indexOf(item.dataKey);
  if (index > -1) {
    formData.value.bonus.splice(index, 1);
  } else {
    if (getTotalSelectedCount() < 10) {
      formData.value.bonus.push(item.dataKey);
    } else {
      uni.showToast({
        title: '最多只能选择10个标签',
        icon: 'none'
      });
    }
  }
};

const toggleSubsidyAllowance = (item) => {
  const index = formData.value.subsidy.indexOf(item.dataKey);
  if (index > -1) {
    formData.value.subsidy.splice(index, 1);
  } else {
    if (getTotalSelectedCount() < 10) {
      formData.value.subsidy.push(item.dataKey);
    } else {
      uni.showToast({
        title: '最多只能选择10个标签',
        icon: 'none'
      });
    }
  }
};

// 检查标签是否被选中
const isAdvantageSelected = (dataKey) => {
  return formData.value.advantage.includes(dataKey);
};

const isWelfareSelected = (dataKey) => {
  return formData.value.benefits.includes(dataKey);
};

const isSalaryBenefitSelected = (dataKey) => {
  return formData.value.bonus.includes(dataKey);
};

const isSubsidyAllowanceSelected = (dataKey) => {
  return formData.value.subsidy.includes(dataKey);
};

// 获取总选择数量
const getTotalSelectedCount = () => {
  return formData.value.advantage.length + 
         formData.value.benefits.length + 
         formData.value.bonus.length + 
         formData.value.subsidy.length;
};

// 提交表单
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    const submitData = {
      companyId: companyId.value,
      advantage: formData.value.advantage.length > 0 ? formData.value.advantage.join(' ') : '',
      benefits: formData.value.benefits.length > 0 ? formData.value.benefits.join(' ') : '',
      bonus: formData.value.bonus.length > 0 ? formData.value.bonus.join(' ') : '',
      subsidy: formData.value.subsidy.length > 0 ? formData.value.subsidy.join(' ') : ''
    };

    await modifyCompanyInfoApi(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
      duration: 2000
    });

    // 发送事件通知公司详情页面重新获取数据

    
    // 跳转回编辑企业页面
      setTimeout(() => {
          uni.$emit('companyInfoUpdated');
        uni.navigateBack();
    }, 1000);

  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败",
      icon: "none",
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 初始化页面数据
const initPageData = () => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  
  if (options.advantage) {
    const advantage = decodeURIComponent(options.advantage || '');
    formData.value.advantage = advantage ? advantage.split(' ').filter(item => item.trim()) : [];
  }
  
  if (options.benefits) {
    const benefits = decodeURIComponent(options.benefits || '');
    formData.value.benefits = benefits ? benefits.split(' ').filter(item => item.trim()) : [];
  }
  
  if (options.bonus) {
    const bonus = decodeURIComponent(options.bonus || '');
    formData.value.bonus = bonus ? bonus.split(' ').filter(item => item.trim()) : [];
  }
  
  if (options.subsidy) {
    const subsidy = decodeURIComponent(options.subsidy || '');
    formData.value.subsidy = subsidy ? subsidy.split(' ').filter(item => item.trim()) : [];
  }
};

onMounted(async () => {
  try {
    // 初始化页面数据
    initPageData();
    // 加载基础数据
    await loadCompanyAdvantageData();
  } catch (error) {
    console.error('组件数据加载失败:', error);
  }
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
}

.save-btn {
  width: 100%;
  height: 60rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 28rpx;
  border: none;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn[disabled] {
  background-color: #c0c0c0;
  color: #fff;
}

.container {
  padding: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

/* 选择数量提示样式 */
.selection-count {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.count-text {
  font-size: 28rpx;
  color: #007aff;
  font-weight: 500;
}

/* 标签选择样式 */
.tag-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  padding: 20rpx 0;
  width: 100%;
  box-sizing: border-box;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background-color: #f8f9fa;
  border-radius: 25rpx;
  border: 2rpx solid #e9ecef;
  transition: all 0.3s ease;
  cursor: pointer;
  min-width: 120rpx;
  box-sizing: border-box;
}

.tag-item:hover {
  background-color: #e9ecef;
  transform: translateY(-2rpx);
}

.tag-item.selected {
  background-color: #e6f7ff;
  border-color: #007aff;
  color: #007aff;
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
}

.tag-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
}

.tag-text {
  font-size: 28rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.tag-item.selected .tag-text {
  color: #007aff;
  font-weight: 500;
}

/* 加载状态和错误处理样式 */
.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  border: 2rpx dashed #ddd;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style>
